<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
        <!-- 给 TodoHeader组件绑定一个事件 -->
        <TodoHeader @recive="recive" />
        <!-- 给 TodoList组件传送 data 中的 todos -->
        <TodoList :todoList="todos" :changeCheck="changeCheck" :todoDelete="todoDelete" />
        <TodoFooter :todoList="todos" @checkAll="checkAll" @delDone="delDone" />
      </div>
    </div>
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader'
import TodoList from './components/TodoList'
import TodoFooter from './components/TodoFooter'

export default {
  name: 'App',
  components: {
    TodoHeader,
    TodoList,
    TodoFooter
  },
  data() {
    return {
      // 实时更新数据，记得使用JSON.parse将字符串转换为js代码，并防止其值为null
      todos: JSON.parse(localStorage.getItem('todos')) || []
    }
  },
  methods: {
    // 添加新的事件
    recive(o) {
      this.todos.unshift(o)
    },
    // 根据收到的 id，修改 done的数值
    changeCheck(id) {
      this.todos.forEach(e => {
        if (e.id === id) e.done = !e.done
      })
    },
    // 根据收到的 id，删除对应的todo
    todoDelete(id) {
      this.todos = this.todos.filter(todo => todo.id !== id)
    },
    // 根据收到的全选按钮的状况，调整done
    checkAll(done) {
      this.todos.forEach(todo => (todo.done = done))
    },
    // 删除已完成的任务
    delDone() {
      confirm('是否删除所有已完成的任务？')
      this.todos = this.todos.filter(todo => !todo.done)
    }
  },
  watch: {
    todos: {
      // 开启深度监视，以保留 done的状态
      deep: true,
      handler(value) {
        // 当 todos发生变化时，存入变化后的新 todos，记得使用JSON.stringify将其转化为字符串
        localStorage.setItem('todos', JSON.stringify(value))
      }
    }
  }
}
</script>

<style>
/* base */
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset o 1px 0 rgba(255, 255, 255, 0.2), 1 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}

.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>